/**
 * @file key_fota.c
 * @brief 
 * @author  ()
 * @version 1.0
 * @date 2024-11-04
 * @ingroup flash
 * @copyright Copyright (C) 2019 Queclink Wireless Solutions (ShenZhen) Co., Ltd. All Rights Reserved.
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2024-11-04 <td>1.0     <td>     <td>内容
 * </table>
 */
#include "key_fota.h"
#define LOG_TAG   "PARM"
#include "easylog/elog.h"


#include "global.h"

#include "aadl/flash.h"
#include "flash/flash_main.h"


int32_t save_fota_flag(char *flag_str)
{
    assert_ptr_ret(flag_str, -EPERM);   
    // #define FOTA_OK_STR    "PASS" /* 固件更新成功, 只能由 bootloader 置位 */
    // #define FOTA_ERR_STR   "FAIL" /* 固件更新失败, 只能由 bootloader 置位 */
    // #define FOTA_RDY_STR   "REDY" /* 固件下载成功, 等待升级, 只能由 APP 置位 */
    // #define FOTA_IDLE_STR  "IDLE" /* 空闲, 没有固件升级业务, 只能由 APP 置位 */
    // #define FOTA_START_STR "STRT" /* 开始下载固件, 只能由 APP 置位 */
    // 1. 标志检查
    if (0 != strcmp(flag_str, FOTA_OK_STR) 
            && 0 != strcmp(flag_str, FOTA_ERR_STR)
            && 0 != strcmp(flag_str, FOTA_RDY_STR) 
            && 0 != strcmp(flag_str, FOTA_IDLE_STR) 
            && 0 != strcmp(flag_str, FOTA_START_STR) ) {
        log_e("fota flag is illegal!\r\n");
        return -EPERM;
    }

    // 2. 写入标志
    int32_t ret = aad_flash_direct_write(FILE_OTA_FLAG_ID, 0, (const uint8_t *)flag_str, strlen(flag_str), AADL_WAIT | AADL_KEEP_OUTSIDE , 0);
    if (ret != 0) {
        ret = aad_flash_direct_write(FILE_OTA_FLAG_ID, 0, (const uint8_t *)flag_str, strlen(flag_str), AADL_WAIT | AADL_KEEP_OUTSIDE , 0);
        log_i("Fail to set ota flag id, reason: %d", ret);

        return ret;
    }
    
    return ret;
}


/**
 * @brief 设置升级就绪标志
 */
int32_t save_fota_ready(void)
{
    return save_fota_flag("REDY");
}


/**
 * @brief 设置升级空闲标志
 */
int32_t save_fota_idle(void)
{
    return save_fota_flag("IDLE");
}

/**
 * @brief 读取升级标志
 * @param  fota_flag        升级标志接收缓存
 * @param  fota_flag_len    传入缓存大小
 * @return int32_t 标志有效状态 > 0 有效, 0 无效
 */
int32_t load_fota_flag(char *fota_flag, uint32_t fota_flag_len) 
{
    int32_t rd_len = 0;
    char fota_mark[FOTA_MARK_MAX_SIZE] = {'\0'};

    rd_len = aad_flash_direct_read(FILE_OTA_FLAG_ID, FOTA_MARK_OFFSET, (uint8_t *)fota_mark, sizeof(fota_mark)-1);
    if (rd_len > 0) {
        if (strncmp(fota_mark, FOTA_OK_STR, strlen(FOTA_OK_STR)) == 0 ||
            strncmp(fota_mark, FOTA_ERR_STR, strlen(FOTA_OK_STR)) == 0 ||
            strncmp(fota_mark, FOTA_RDY_STR, strlen(FOTA_OK_STR)) == 0 ||
            strncmp(fota_mark, FOTA_IDLE_STR, strlen(FOTA_OK_STR)) == 0 ||
            strncmp(fota_mark, FOTA_START_STR, strlen(FOTA_OK_STR)) == 0) {
            snprintf(fota_flag, fota_flag_len, "%s", fota_mark);
        }
    }

    return rd_len;
}